package com.itheima.activiti.controller;

import org.activiti.api.process.model.ProcessInstance;
import org.activiti.api.process.model.builders.ProcessPayloadBuilder;
import org.activiti.api.process.runtime.ProcessRuntime;
import org.activiti.api.runtime.shared.query.Page;
import org.activiti.api.runtime.shared.query.Pageable;
import org.activiti.api.task.model.Task;
import org.activiti.api.task.model.builders.TaskPayloadBuilder;
import org.activiti.api.task.runtime.TaskRuntime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * TODO
 *
 * @author fgy
 * @version 1.0
 * @date 2021/6/21 15:05
 */
@RestController
public class Mycontroller {
    @Autowired
    private ProcessRuntime processRuntime;
    @Autowired
    private TaskRuntime taskRuntime;
//请假 实质是启动实例  并完成请假单
    @GetMapping("/holiday")
    public void holiday() {
        ProcessInstance pi = processRuntime.start(ProcessPayloadBuilder.start()
//                .withVariable()
//                .withVariables()
//                .withBusinessKey()
                .withProcessDefinitionKey("myProcess_1")
                .build());

        Page<Task> tasks = taskRuntime.tasks(Pageable.of(0, 10), TaskPayloadBuilder.tasks().withProcessInstanceId(pi.getId()).build());
        if (tasks.getTotalItems() > 0) {
            for (Task task : tasks.getContent()) {
//               拾取任务  这里谁登录谁拾取
//                 org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);这个方法
                taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
                System.out.println("任务：" + task);
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
            }
        }
    }

    //审批
    @GetMapping("/examine")
    public void examine() {

//        securityUtil.logInAs("ryandawsonuk");  直接登录会被security拦截  不需要这里模拟了
        Page<Task> taskPage = taskRuntime.tasks(Pageable.of(0, 10));
        if (taskPage.getTotalItems() > 0) {
            for (Task task : taskPage.getContent()) {
//               拾取任务  这里谁登录谁拾取
//                 org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(username);这个方法
                taskRuntime.claim(TaskPayloadBuilder.claim().withTaskId(task.getId()).build());
                System.out.println("任务：" + task);
                taskRuntime.complete(TaskPayloadBuilder.complete().withTaskId(task.getId()).build());
            }
        }
        Page<Task> taskPage2 = taskRuntime.tasks(Pageable.of(0, 10));
        if (taskPage2.getTotalItems() > 0) {
            System.out.println("任务：" + taskPage2.getContent());
        }

    }
}
